package com.traffic.util;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.traffic.entity.Leaderboard;
import com.traffic.entity.Rank;
import com.traffic.service.LeaderboardService;
import com.traffic.service.RankService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Collections;
import java.util.Random;


@Component
@Slf4j
public class RankUtil {

    @Autowired
    RankService rankService;

    @Autowired
    LeaderboardService leaderboardService;


    //首次插入100条空数据
    //数据库主键清零
    //update ots_leaderboard set id=0;
    //ALTER TABLE ots_leaderboard AUTO_INCREMENT=0;

    public void insertNullRank(){

        Leaderboard led = new Leaderboard();
        for(int i=1;i<=100;i++){

            led.setId(new Long(i));
            led.setUserId(new Long(i));

            leaderboardService.save(led);
        }
    }


    //测试随机生成数据
    public void insertNullRankData(String rtype){

        long  t = System.currentTimeMillis();
        Random rand = new Random(t);
       // Rank r = new Rank();
        for(int i=1;i<=302;i++){


        //    r.setUserId(new Long(i));
        //    r.setHisMileage(new Double(rand.nextDouble()*1000));

        //    rankService.save(r);

            UpdateWrapper<Rank> wrapper = new UpdateWrapper<>();
            rankService.update(wrapper.eq("id",i).set(rtype, new Double(rand.nextDouble()*5)));

        }


    }

    //根据类型分别取前100排序
    public void sortRank(String rtype){

        QueryWrapper<Rank> wrapper = new QueryWrapper<>();

        List<Rank> ranks = rankService.list(wrapper.orderByDesc(rtype).last("limit 0 , 100"));


        int j = 1 ;
        for(Rank i :ranks){
            UpdateWrapper<Leaderboard> Lwrapper = new UpdateWrapper<>();
            leaderboardService.update(Lwrapper.eq("id",j).set(rtype,i.getUserId()));
            j++;
        }

    }


    //测试：随机插入用户
    public void updateRank(String rtype){

        Leaderboard led = new Leaderboard();
        Random r = new Random(20);
        for(int i=1;i<=100;i++){

            UpdateWrapper<Leaderboard> Lwrapper = new UpdateWrapper<>();
            leaderboardService.update(Lwrapper.eq("id",i).set(rtype, new Long(r.nextInt(302))));
        }

    }

}
